/**
 * 广发银行信用卡抓取流程处理
 * @type {{CREDIT: string}}
 */

/**
 * 信用卡业务处理主干流程
 */
function credit_crawl(creditCardAllData,sessionInfo) {

    //如果为相同卡，不执行后续业务逻辑
    if(isSameCard()===true)return;
    nextCard();
    //抓取卡信息
    cgb_credit_handle.crawlCardInfo();
    //解析卡信息
    cgb_credit_handle.parseCardInfo(creditCardAllData);
    /*
     *  抓取和解析未出账单，
     *  因未出账单中存在翻页处理，存在前后依赖关系，所以抓取和解析流程合并在一起
     *  但不影响抓取和解析具体方法的拆分,后期看是否可以进一步优化
     */
    cgb_credit_handle.crawlAndParseUndo(creditCardAllData,sessionInfo);
    //抓取已出账单
    cgb_credit_handle.crawlDONE();
    //解析已出账单
    return cgb_credit_handle.parseDONE(creditCardAllData);
}


var PATTERN_SHORT_MONTH = "yyyyMM";
var isDebug = false;
//本期新增等于支出之和
var new_change = 0;
//还款日，当本期无需还款的时候计算还款日
var day = "";





/**
 * 判断是否为相同的卡
 * @returns {boolean}
 */
function isSameCard(){
    //默认不是相同的卡
    var isSameCard = false;
    //这里如果一张卡做过变更，可能会有两个卡号（session_iAccountInfo会有两个节点数据），
    //这种情况本质是一张卡，所以不再抓第二个卡号，并把卡号链接，以","隔开
   if(context.get(keys.IS_SAME_CARD)!=null){
       var last4No=context.get(keys.IS_SAME_CARD);
       if(last4No.contains(getLast4Str(baseMap.get(keys.USER_ACCOUNTNO)))){
           jointCardNo(context.get(keys.CREDIT_CARD),baseMap.get(keys.USER_ACCOUNTNO));
           return isSameCard = true;
       }
   }
    return isSameCard;
}


/**
 * 封装广发银行登录成功后，抓取过程的主要业务方法
 * @type {{crawlCardInfo: cgb_credit_handle.crawlCardInfo, parseCardInfo: cgb_credit_handle.parseCardInfo, crawlAndParseUndo: cgb_credit_handle.crawlAndParseUndo, crawlDONE: cgb_credit_handle.crawlDONE, parseDONE: cgb_credit_handle.parseDONE}}
 */
var cgb_credit_handle={
    /**
     * 抓取卡信息
     */
     crawlCardInfo:function(){
        try {
            var paramsMap = new HashMap();
            paramsMap.put("EMP_SID", baseMap.get(keys.EMP_SID).trim());
            paramsMap.put("accountNo",baseMap.get(keys.USER_ACCOUNTNO));
            paramsMap.put("submitTimestamp", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
            paramsMap.put("trxCode", "b010101");
            var url = generateURL(urls.CRTBILL_URL, paramsMap);
            var jsonStr = ajax_get(url);
            logger.info(BankCode.CGB + "卡" + card + " 卡信息开始,taskkey {}",context.get(Constants.LUA_TASK_KEY))
            storeDataToFile(context, jsonStr,  card+"_card_"+(card_Id++)+".html");
            context.put(keys.CARD_INFO,jsonStr);
        } catch (e) {
            logger.error("taskKey={} 卡信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    },

    /**
     * 解析卡信息
     * @param creditCardAllData
     */
     parseCardInfo:function(creditCardAllData){
        try {
            creditCardAllData.setNameOnCard(baseMap.get(keys.USER_NAME));
            var jsonStr=context.get(keys.CARD_INFO);
            var inObj = JSON.parseObject(jsonStr);
            if(inObj==null){
                logger.info(BankCode.CGB + "ajax_get返回为null,taskkey {}",context.get(Constants.LUA_TASK_KEY));
                throw new BankException(BankConstants.BACR_99602_20,"会话超时，请重新登录!");
            }

            //请求返回的Json中，em为错误信息，如果em不为空，则获取到并做异常处理
            if (inObj.getString("em").contains("会话已超时，请重新登录")) {
                logger.info(BankCode.CGB + "会话超时请重新登录,taskkey {}", context.get(Constants.LUA_TASK_KEY));
                throw new BankException(BankConstants.BACR_99602_20, "会话超时，请重新登录!");
            } else if (inObj.getString("em").contains("抱歉！由于网络原因，未收到执行结果")) {
                logger.info(BankCode.CGB + "由于网络原因，未收到执行结果,taskkey {}", context.get(Constants.LUA_TASK_KEY));
                throw new BankException(BankConstants.BALO_21301_10, "网络原因，系统繁忙");
            }


            //开始正式解析
            if(inObj.getString("em") == null || inObj.getString("em") == "") {
                //返回的Json中cd为卡信息，获取到卡信息继续解析
                var cd = inObj.getJSONObject("cd");
                //获取到部分卡信息
                var accountNo = cd.getString("accountNo");// 卡号
                creditCardAllData.setFullCardNum(accountNo);
                creditCardAllData.setCardNum(accountNo.substring(accountNo.length() - 4));
                var billDate = cd.getString("billDate");// 本期账单日

                var currentRtLmtDate = cd.getString("currentRtLmtDate");// 到期还款日

                //初始化未出账单的billAllData
                var alldata =getUNDoneBillAllDataHeaderData(creditCardAllData);
                var billdate = new Date(MyDateUtil.convergeTime(billDate));
                //账单日放入全局map，供后续业务方法中使用
                baseMap.put(keys.DONE_BILLDATE,billdate)
                var c = Calendar.getInstance();
                c.setTime(billdate);
                c.add(Calendar.MONTH, 1);
                // 账单YEAR份为账单日
                alldata.setBillMonth(TimeUtil.getTimeStr(c.getTime(), "yyyy-MM"));
                alldata.setBillDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(c.getTime(), "yyyy-MM-dd")));
                var paymentDate = Calendar.getInstance();
                if (StringUtils.isNotBlank(currentRtLmtDate) && currentRtLmtDate.length() > 2) {
                    day = currentRtLmtDate.substring(currentRtLmtDate.length() - 2);
                }
                paymentDate.setTimeInMillis(MyDateUtil.convergeTime(currentRtLmtDate));
                paymentDate.add(Calendar.MONTH, 1);
                alldata.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(paymentDate.getTime(), "yyyy-MM-dd")));
                alldata.setNewCharges(GetJiner(String.valueOf(new_change)));
                // logger.info(BankCode.CGB + "卡" + card + " 卡信息成功,taskkey {}", context.get(Constants.LUA_TASK_KEY));

                //解析人民币和美元两种货币消费额度，完成数据填充
                var iCreditCardListArray = cd.getJSONArray("iCreditCardList");

                for (var i = 0; i < iCreditCardListArray.size(); i++) {
                    var iCreditCardList = iCreditCardListArray.getJSONObject(i);
                    var currencyType = iCreditCardList.getString("currencyType");// 货币类型
                    //人民币类型数据获取

                    if(currency_Type.RMB.equals(currencyType)){
                        RMBhandle(iCreditCardList,creditCardAllData,alldata);
                    }

                    //美元类型数据抓取解析
                    if(currency_Type.USD.equals(currencyType)){
                        alldata.setUsdNewBalance(GetJiner(currentRtLmtAmt));
                        alldata.setUsdMinPayment(GetJiner(lastRtnLmtAmt));
                        alldata.setUsdCreditLimit(GetJiner(creditLimitForCard));
                        alldata.setUsdCashLimit(GetJiner(cashLimitForCard));
                    }
                }
            }
        }catch (e) {
            logger.error("taskKey={} 卡信息解析异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }

        /**
         * 填充未出账单中的人民币类型数据
         * @param iCreditCardList
         * @param creditCardAllData
         * @param alldata
         * @constructor
         */
        function RMBhandle(iCreditCardList,creditCardAllData,alldata){
            try {
                logger.info(BankCode.CGB + "卡" + card + " 卡人民币信息开始,taskkey {}", context.get(Constants.LUA_TASK_KEY));
                var creditLimitForCard = iCreditCardList.getString("creditLimitForCard");// 卡消费额度
                var cashLimitForCard = iCreditCardList.getString("cashLimitForCard");// 卡现金额度
                var cashAvailableLimit = iCreditCardList.getString("cashAvailableLimit");// 当前可用现金余额
                var balanceAvailable = iCreditCardList.getString("balanceAvailable");// 可用余额
                var currentRtLmtAmt = iCreditCardList.getString("currentRtLmtAmt");// 本期还款额
                var lastRtnLmtAmt = iCreditCardList.getString("lastRtnLmtAmt");// 本期最低还款额
                //填充数据
                alldata.setNewBalance(GetJiner(currentRtLmtAmt));
                alldata.setMinPayment(GetJiner(lastRtnLmtAmt));
                alldata.setCreditLimit(GetJiner(creditLimitForCard));
                alldata.setCashLimit(GetJiner(cashLimitForCard));
                creditCardAllData.setCreditLimit(GetJiner(creditLimitForCard));
                creditCardAllData.setCashLimit(GetJiner(cashLimitForCard));
                // 如果可用额度大于额度，设置为实际，否则设置为最大
                if (GetJiner(balanceAvailable).doubleValue() <= GetJiner(creditLimitForCard).doubleValue()) {
                    creditCardAllData.setBalance(GetJiner(balanceAvailable));
                } else {
                    creditCardAllData.setBalance(GetJiner(creditLimitForCard));
                }
                // 如果可用现金额度大于现金额度，设置为实际，否则设置为最大
                if (GetJiner(cashAvailableLimit).doubleValue() <= GetJiner(cashLimitForCard).doubleValue()) {
                    creditCardAllData.setCashBalance(GetJiner(cashAvailableLimit));
                } else {
                    creditCardAllData.setCashBalance(GetJiner(cashLimitForCard));
                }
            } catch (e) {
                logger.error("taskKey={} 卡未出账单数据解析异常：{}", context.get(LUA_TASK_KEY), e);
                statCaughtExceptionByJS(context, e);
            }
        }
    },

    /**
     * 抓取和解析未出账单，
     *  因未出账单中存在翻页处理，存在前后依赖关系，所以抓取和解析流程合并在一起
     *  但不影响抓取和解析具体方法的拆分,后期看是否可以进一步优化
     * @param creditCardAllData
     * @param sessionInfo
     */
     crawlAndParseUndo:function(creditCardAllData,sessionInfo){
        var jsonStr=context.get(keys.CARD_INFO);
        var inObj = JSON.parseObject(jsonStr);
        //开始正式解析
        if(inObj.getString("em") == null || inObj.getString("em") == "") {
            //返回的Json中cd为卡信息，获取到卡信息继续解析
            var cd = inObj.getJSONObject("cd");
            var billDate = cd.getString("billDate");// 本期账单日
            //解析人民币和美元两种货币消费额度，完成数据填充
            var iCreditCardListArray = cd.getJSONArray("iCreditCardList");

            //初始化未出账单的billAllData
            var alldata =getUNDoneBillAllDataHeaderData(creditCardAllData);

            for (var i = 0; i < iCreditCardListArray.size(); i++) {
                var iCreditCardList = iCreditCardListArray.getJSONObject(i);
                var currencyType = iCreditCardList.getString("currencyType");// 货币类型
                //人民币类型数据获取
                if(currency_Type.RMB.equals(currencyType)){
                    //抓取未出账单，当天购物明细
                    var curDayHtml=crawlCurDayShoppingSheets(sessionInfo);
                    //解析未出账单，当天购物明细
                    parserUnDoBills(curDayHtml,alldata.getShoppingSheets())
                    //分页处理，抓取未出账单，购物明细
                    pageHandleShoppingSheets(sessionInfo,alldata.getShoppingSheets())
                }
            }
        }

        //以下两个方法
        // 1、抓取未出账单当天购物明细
        // 2、分页处理未出账单购物明细
        // 都属于未出账单流程，所以封装到crawlAndParseUndo中

        /**
         * 1、抓取未出账单当天购物明细
         * @param sessionInfo
         * @returns {*}
         */
        function crawlCurDayShoppingSheets(sessionInfo){
            try {
                sessionInfo.put("currencyType", "156");
                sessionInfo.put("index", "1");
                sessionInfo.put("beginDate", billDate);
                sessionInfo.put("endDate", TimeUtil.getTimeStr(new Date(), "yyyyMMdd"));
                sessionInfo.put("cardNo",baseMap.get(keys.USER_ACCOUNTNO));
                sessionInfo.put("turnPageBeginPos", "1");
                sessionInfo.put("turnPageShowNum", "10");
                sessionInfo.put("bigAccountSrcSign", "0");
                sessionInfo.put("turnPageBeginPage", "1");
                sessionInfo.put("EMP_SID",baseMap.get(keys.EMP_SID));

                logger.info(BankCode.CGB + "卡" + card + " 卡当天交易记录开始,taskkey {}", context.get(Constants.LUA_TASK_KEY));
                var html = ajax_post(urls.CARDINFO_URL_0, sessionInfo);
                storeDataToFile(context, html, card + "_bill_ShoppingSheet_Id_" + (bill_ShoppingSheet_Id++) + ".html");
                return html;
            } catch (e) {
                logger.error("taskKey={} 卡未出账单当天购物明细抓取异常：{}", context.get(LUA_TASK_KEY), e);
                statCaughtExceptionByJS(context, e);
            }
        }

        /**
         * 2、分页处理未出账单购物明细
         * @param sessionInfo
         * @param bills
         */
        function pageHandleShoppingSheets(sessionInfo,bills) {
            try {
                logger.info(BankCode.CGB + "卡" + card + " 卡本期未出账单开始,taskkey {}", context.get(Constants.LUA_TASK_KEY));
                var html = ajax_post("https://ebanks.cgbchina.com.cn/perbank/CR0002.do", sessionInfo);
                storeDataToFile(context, html, card + "_bill_ShoppingSheet_Id_" + (bill_ShoppingSheet_Id++) + ".html");
                //解析已出账单，处理分页
                var turnPageTotalNum = parserUnDoBills(html, bills);
                for (var j = 11; j <= turnPageTotalNum; j += 10) {
                    jiaoyijiluPostMap.put("turnPageBeginPos", String.valueOf(j));
                    var currentPage = j / 10 + 1;
                    jiaoyijiluPostMap.put("turnPageBeginPage", String.valueOf(currentPage));
                    html = ajax_post("https://ebanks.cgbchina.com.cn/perbank/CR0002.do", jiaoyijiluPostMap);
                    storeDataToFile(context, html, card + "_bill_ShoppingSheet_Id_" + (bill_ShoppingSheet_Id++) + ".html");
                    parserUnDoBills(html, bills);
                }
                logger.info(BankCode.CGB + "卡" + card + " 卡本期未出账单结束,taskkey {}", context.get(Constants.LUA_TASK_KEY));
                logger.info(BankCode.CGB + "卡" + card + " 卡人民币信息成功,taskkey {}", context.get(Constants.LUA_TASK_KEY));

            } catch (e) {
                logger.error("taskKey={} 未出账单分页购物明细处理异常：{}", context.get(LUA_TASK_KEY), e);
                statCaughtExceptionByJS(context, e);
            }
        }
    },


    /**
     * 抓取已出账单
     */
     crawlDONE:function(){
        try {
            //用于存放12个月的抓取结果
            var doneMap=new HashMap();
            //循环抓取一年的已出账单数据
            for (var i = 0; i < 12; i++) {
                logger.info("taskKey={} 已出账单信息抓取第【{}】次", context.get(LUA_TASK_KEY),i+1);
                var billDate=baseMap.get(keys.DONE_BILLDATE);
                // 获取当前月份
                var currentMonth = getYearMonthStr(billDate) ;
                //月份String偏移，如输入"201411","yyyyMM",5 -->"201504"
                var month = monthStringAmount(currentMonth, PATTERN_SHORT_MONTH, -i);
                var paramsMap = new HashMap();
                paramsMap.put("currencyType", "");
                paramsMap.put("creditCardNo",baseMap.get(keys.USER_ACCOUNTNO));
                paramsMap.put("billDate", month);
                paramsMap.put("billType", "1");
                paramsMap.put("abundantFlag", "0");
                paramsMap.put("terseFlag", "0");
                paramsMap.put("showWarFlag", "0");
                paramsMap.put("EMP_SID", baseMap.get(keys.EMP_SID));
                var url = generateURL(urls.BILLMAIN_URL, paramsMap);

                var jsonStr ="";
                //网络问题，多次尝试
                for(var k=0;k<5;k++){
                    jsonStr = ajax_get(url);
                    if(jsonStr.contains("账单系统出现异常，请稍后再查询")){
                        Thread.sleep(1000);
                        continue;
                    }else{
                        break;
                    }
                }
                storeDataToFile(context, jsonStr, card+"_credit_bill_list_"+(bill_ID++)+".html");
                //存放12月的已出账单详情结果
                doneMap.put(i,jsonStr);
            }

            //放入当前上下文
            context.put(keys.DONE_MAP,doneMap);
        } catch (e) {
            logger.error("taskKey={} 已出账单信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    },

    /**
     * 解析已出账单详情
     * @param creditCardAllData
     * @returns {*}
     */
     parseDONE:function(creditCardAllData) {
        try {
            //获取账单map
            var doneMap=context.get(keys.DONE_MAP);
            //循环解析12个月的已出账单
            for (var i = 0; doneMap!=null&&i<doneMap.size(); i++) {
                logger.info("taskKey={} 已出账单信息解析第【{}】次", context.get(LUA_TASK_KEY),i+1);
                var jsonStr= doneMap.get(i);
                //解析账单
                var billmap=parserBills3(creditCardAllData,jsonStr);
                //如果为null 则根据卡号和账单日重新获取一个map
                if (billmap == null) {
                    //无购物明细,只创建表头
                    // 获取当前月份
                    var billDate = baseMap.get(keys.DONE_BILLDATE);
                    var currentMonth = getYearMonthStr(billDate) ;
                    var month = monthStringAmount(currentMonth, PATTERN_SHORT_MONTH, -i);
                    billmap =getBillMap(month,creditCardAllData,baseMap.get(keys.USER_ACCOUNTNO),billDate);
                }

            }
            logger.info(BankCode.CGB + "卡" + card + " 卡已出账单结束,taskkey {}",context.get(Constants.LUA_TASK_KEY));
            var bills=creditCardAllData.getBills();
            if (bills != null && bills.size() > 0) {
                for each (var billAllData in bills) {
                    //处理分期信息
                    parseInstallment(billAllData);
                }
            }

            //补充未出账单的上月账单金额和已出账单金额等数据
            setUndoneData(creditCardAllData);

            context.put(keys.IS_SAME_CARD,baseMap.get(keys.LAST4No));
            context.put(keys.CREDIT_CARD,creditCardAllData);
            return creditCardAllData;
        } catch (e) {
            logger.error("taskKey={} 已出账单信息解析异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtExceptionByJS(context, e);
        }
    }
}

/**
 * 判断是否为同一张卡时的数据处理
 * @param cardAllData
 * @param accountNo
 */
function jointCardNo(cardAllData,  accountNo) {
    var cardno = cardAllData.getFullCardNum();
    var last4no = cardAllData.getCardNum();
    cardno = cardno+","+accountNo;
    last4no = last4no+","+getLast4Str(accountNo);
    cardAllData.setCardNum(last4no);
    cardAllData.setFullCardNum(cardno);
}


/**
 * 信用卡,补充未出账单的上月账单金额和已出账单金额等数据
 * @param creditCardAllData
 */
function setUndoneData(creditCardAllData) {
    var bills=creditCardAllData.getBills();
    for(var i=0;i<bills.size();i++){
        //遍历出未出账单，填充从最新已出账单类型中获取的上月账单金额
        if(bills[i].getBillType().equals("UNDONE")){
            bills[i].setLastBalance(baseMap.get(keys.UNDO_LAST_NEWBALANCE));
            bills[i].setNewBalance(baseMap.get(keys.UNDO_NEWBALANCE));
        }
    }
}


/**
 * 已出账单没有数据时,构建空表头数据
 * @param month
 * @param creditCardAllData
 * @param accountno
 * @param billDate
 * @returns {LinkedHashMap}
 */
function getBillMap( month,  creditCardAllData,  accountno,  billDate) {
    var billMap = new LinkedHashMap();
    var accountnos = getLast4Str(accountno);
    //现获取到一个可用的已出账单的billAllData
    var billAllData = getDoneBillAllDataHeaderData(creditCardAllData);
    //var billAllData = getBillAllData();
    billAllData.setBillMonth(getYYYYMM(month));
    billAllData.setCashLimit(creditCardAllData.getCashLimit());
    billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBankName("广发银行");
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(getYYYYMMDD(month,billDate)));
    billAllData.setBillType("DONE");
    billMap.put(accountnos, billAllData);
    return billMap;
}

function getYYYYMM(date){
    var year = date.substring(0,4);
    var month = date.substring(4);
    return year+"-"+month;
}
function getYYYYMMDD( date, billDate){
    var year = date.substring(0,4);
    var month = date.substring(4);
    var cal = Calendar.getInstance();
    cal.setTime(billDate);
    var day = cal.get(Calendar.DAY_OF_MONTH)
    if(equals("02",month)&&day>28){
        day = "28"
    }
    if(String.valueOf(day).length == 1){
        day="0"+day;
    }
    return year+"-"+month+"-"+day;
}

function getYearMonthStr(billDate) {
    var cal = Calendar.getInstance();
    var day = cal.get(Calendar.DAY_OF_MONTH);
    var date = "";
    if(billDate!=null){
        cal.setTime(billDate)
        billDate = cal.get(Calendar.DAY_OF_MONTH);
        if(day<billDate){
            cal.setTime(new Date());
            cal.add(Calendar.MONTH,-1);
            date = DateFormatUtils.format(cal.getTime(), PATTERN_SHORT_MONTH);
        }else{
            date = DateFormatUtils.format(new Date(), PATTERN_SHORT_MONTH);
        }
    }else{
        date = DateFormatUtils.format(new Date(), PATTERN_SHORT_MONTH);
    }
    return date;
}

// 月份String偏移，如输入"201411","yyyyMM",5 -->"201504"
function monthStringAmount( monthStr,  format,  amount){
    // String转date
    var arr = new String(format);
    // arr.add(format);
    var date = DateUtils.parseDate(monthStr,arr);

    // date偏移
    date = DateUtils.addMonths(date, amount);

    // date转String
    return DateFormatUtils.format(date, format);
}

/**
 * 获取字符串后四位字符
 *
 * @param str
 * @return
 */
function getLast4Str( str) {
    if (str != null && str.length() >= 4) {// 从混淆后的卡号中取出后四位
        return str.substring(str.length() - 4);
    } else {
        return str
    }
}


/**
 * 解析首页拿到 _emp_sid
 *
 * @param html
 * @return
 */
function parseEmpSid( html) {
    var _emp_sidStr = getLineFromHtml("_emp_sid", html);
    if (_emp_sidStr == null) {
        return null;
    }
    var temp = _emp_sidStr.split("'");
    if (temp.length == 3) {
        return temp[1];
    }

    return null;
}

// 从html中找到指定的变量所在的最近一行
function getLineFromHtml( targetStr,  htmlStr) {
    if (StringUtils.isBlank(htmlStr)) {
        return null;
    }
    var arrays = htmlStr.split("\n");
    for each (var str in arrays) {
        if (str.contains(targetStr)) {
            return str;
        }
    }
    return null;
}

/**
 * 解析未出账单具体逻辑
 * @param html
 * @param bills
 * @returns {number}
 */
function parserUnDoBills( html,  bills) {
    var turnPageTotalNum = 0;
    if (StringUtils.isNotBlank(html)) {
        var map = JSON.parseObject(html);
        if (map != null) {

            var cd =  map.get("cd");
            if (cd != null) {
                var total =  cd.get("turnPageTotalNum");
                if (StringUtils.isNotBlank(total) && total.matches("\\d{1,}")) {
                    turnPageTotalNum = Integer.valueOf(total);
                }
                var credResult =  cd.get("credResult");
                var card_num = getLast4Str(cd.get("accountNo")==null? cd.get("cardNo"): cd.get("accountNo"));
                if (credResult != null) {
                    for each (var map2 in credResult) {
                        var jiaoyiri =  map2.get("transferDate");
                        var ruzhangri = map2.get("recordDate");
                        var zhaiyao = map2.get("noteCode");
                        if (StringUtils.isNotBlank(zhaiyao)) {
                            zhaiyao = zhaiyao.trim();
                        } else {
                            zhaiyao = "";
                        }
                        var jiaoyijiner =  map2.get("transamt");
                        var jiaoyihuobi =  map2.get("currency");
                        if (jiaoyihuobi != null && jiaoyihuobi.equals("156")) {
                            jiaoyihuobi = "人民币";
                        }
                        card_num =  map2.get("last4OfCardNo");
                        var debitCreditCode =  map2.get("debitCreditCode");
                        if (!debitCreditCode.contains("-")) {
                            jiaoyijiner = "-" + jiaoyijiner;
                        } else {// 本期新增等于支出之和
                            new_change = new_change + GetJiner(jiaoyijiner).doubleValue();
                        }
                        var ruzhangjiner = jiaoyijiner;
                        if (StringUtils.isBlank(jiaoyiri) || !jiaoyiri.matches("\\d{4}\\d{2}\\d{2}")) {
                            continue;
                        }

                        var billdatail = createExpense(++billId, card_num, jiaoyiri, zhaiyao, jiaoyihuobi, jiaoyijiner, ruzhangri,
                            ruzhangjiner);
                        bills.add(billdatail);
                    }
                } else {
                    credResult =  cd.get("iTodayDetailList");

                    if (credResult != null) {
                        for each (var map2 in credResult) {
                            var jiaoyiri =  map2.get("tradeDate");
                            var ruzhangri =  map2.get("tradeDate");
                            var zhaiyao =  map2.get("merchantName");
                            var oldMerchantName = map2.get("oldMerchantName");
                            if (StringUtils.isNotBlank(zhaiyao)) {
                                zhaiyao = zhaiyao.trim();
                            } else {
                                zhaiyao = "";
                            }
                            var jiaoyijiner =  map2.get("transAmt");
                            var jiaoyihuobi =  map2.get("transCurr");
                            if (jiaoyihuobi != null && jiaoyihuobi.equals("156")) {
                                jiaoyihuobi = "人民币";
                            }
                            var transType =  map2.get("transType");
                            if (transType.contains("PY")) {
                                jiaoyijiner = "-" + jiaoyijiner;
                            } else {// 本期新增等于支出之和
                                new_change = new_change + GetJiner(jiaoyijiner).doubleValue();
                            }
                            var ruzhangjiner = jiaoyijiner;
                            if (StringUtils.isBlank(jiaoyiri) || !jiaoyiri.matches("\\d{4}\\d{2}\\d{2}")) {
                                continue;
                            }

                            var billdatail = createExpense(++billId, card_num, jiaoyiri, zhaiyao, jiaoyihuobi, jiaoyijiner, ruzhangri,
                                ruzhangjiner);
                            if (oldMerchantName != null) {
                                billdatail.setTransAddr(oldMerchantName);
                            }
                            bills.add(billdatail);
                        }
                    } else {
                        logger.error("解析未出账单失败,taskkey {}",context.get(Constants.LUA_TASK_KEY));
                    }
                }
            } else {
                logger.error("解析未出账单失败,taskkey {}",context.get(Constants.LUA_TASK_KEY));
            }
        } else {
            logger.error("解析未出账单失败,taskkey {}",context.get(Constants.LUA_TASK_KEY));
        }

    }
    return turnPageTotalNum;
}

/**
 * 从账单中挑出分期<br>
 * "shoppingsheet_id": "e91d7fe2-3aac-11e7-8406-00163e0dfac7",<br>
 * "trans_date": "2017-05-16 00:00:00",<br>
 * "post_date": "2017-05-16",<br>
 * "installment_type": "CONSUME",<br>
 * "total_month": 3,<br>
 * "current_month": 1,<br>
 * "currency_type": "CNY",<br>
 * "amount_money": 103.33,<br>
 * "installment_desc": "样样行消费分期17136070917"<br>
 *
 * @param creditBill
 */
function parseInstallment( creditBill) {
    if (creditBill != null && creditBill.getShoppingSheets() != null) {
        var list = creditBill.getShoppingSheets();
        var map = new LinkedHashMap();
        for each (var expense in list) {// 从交易记录中得到分期手续费那条记录
            var title = expense.getDescription();
            if (title != null && (title.contains("分期手续费")&&title.contains("/") || (title.contains("财智金")&&title.contains("手续费")&&title.contains("/")))) {
                var fenqiId = title.substring(title.indexOf("手续费") + 3).trim();
                var install = getInstallment();
                // (CONSUME-消费;CASH-现金;BILL-账单）
                if (title.contains("现金") || title.contains("财智金")) {// 根据标题，设置分期类型
                    install.setInstallmentType("CASH");
                } else if (title.contains("消费")) {
                    install.setInstallmentType("CONSUME");
                } else if (title.contains("账单")) {
                    install.setInstallmentType("BILL");
                } else {
                    logger.error("分期类型出现错误 ,{} ,taskkey {}", title,context.get(Constants.LUA_TASK_KEY));
                    install.setInstallmentType("BILL");
                }
                // 将手续费相关填到分期内容中
                logger.info("CGB---title: {} ,taskkey {}",title,context.get(Constants.LUA_TASK_KEY));
                var title1 = title.substring(0, title.indexOf("/"));
                title1 = title1.replace("手续费", "");
                install.setInstallmentDesc(title1);
                install.setHandingFee(expense.getAmountMoney());
                install.setCurrencyType("CNY");
                install.setPostDate(expense.getPostDate());
                install.setTransDate(expense.getTransDate());
                install.setHandingfeeDesc(title);
                var month = fenqiId.substring(fenqiId.indexOf("/") + 1);
                install.setCurrentMonth(Integer.valueOf(month));
                map.put(fenqiId, install);// 将分期id，和当前期放到map里
            }
        }
        for each (var expense in list) {
            var title = expense.getDescription();
            if (title != null && (title.contains("分期") || title.contains("财智金")) && !title.contains("冲账")) {
                for each (var string in map.keySet()) {
                    if(title.indexOf("手续费")>0&&title.indexOf("划账手续费")<0){
                        continue;
                    }
                    if (title.contains(string.substring(0,string.indexOf("/")-1))) {// 根据分期id和当前期，取到分期记录，然后填充
                        var install = map.get(string);
                        if(title.contains("划账手续费")){
                            install.setTransferFee(expense.getAmountMoney());
                            install.setTransferfeeDesc(title);
                        }else{
                            install.setAmountMoney(expense.getAmountMoney());
                            var total = title.substring(title.length() - 3, title.length() - 1);
                            install.setTotalMonth(Integer.valueOf(total));
                        }
                        install.setShoppingsheetId(expense.getId());
                    }
                }
            }
        }
        if (map.size() > 0) {
            var listInstall=creditBill.getInstallments();
            listInstall.add(map.values());
            // creditBill.setInstallments(new ArrayList(map.values()));
        }
    }
}

/**
 * 通过网页解析账单
 *
 * @param map
 * @param jsonStr
 * @return
 */
function parserBills3_(creditCardAllData, map,  jsonStr) {
    var map=new HashMap();
    var doc = Jsoup.parse(jsonStr);
    var billdate = null;
    var reportPanel4 = doc.select("#reportPanel4");
    var fixBand5 = doc.select("font");
    if (fixBand5.size() < 1) {
        logger.error(BankCode.CGB + " 账单周期解析不符规则 长度为 {},taskkey {}", fixBand5.size(),context.get(Constants.LUA_TASK_KEY));
        return null;
    }
    var startData = null;
    var endData = null;
    var infos = new LinkedHashMap();
    var BillDateflag = false;
    for (var i = 0; i < fixBand5.size(); i++) {
        var text = fixBand5.get(i).text();
        if (text.contains("账单周期")) {
            text = fixBand5.get(i + 1).text();
            var date = text.split("-");
            startData = date[0].replaceAll(" ", "").trim();
            endData = date[1].replaceAll(" ", "").trim();
            // creditBill.setBillDate(processDate(endData));
            billdate = new Date(MyDateUtil.convergeTime(endData));
            map.put("beginDate", startData);
            map.put("endDate", endData);
            BillDateflag = true;
            break;
        }
    }
    if (!BillDateflag) {// 没有解析到账单周期
        logger.error(BankCode.CGB + " 么有解析到账单周期,taskkey {}",context.get(Constants.LUA_TASK_KEY));
        return null;
    }
    var accountInfoFlag = false;
    var fixBand2 = reportPanel4.select("#groupFooter1").select("tr");
    if (fixBand2.size() > 0) {
        for each (var element in fixBand2) {

            var tds = element.select("td");
            if (tds.size() < 5) {
                continue;
            }
            //现获取到一个可用的已出账单的billAllData
            var creditBill = getDoneBillAllDataHeaderData(creditCardAllData);
            // var creditBill = getBillAllData();
            var cardNumber = tds.get(0).text().trim();
            // 上期账单金额
            var newBalance = tds.get(1).text().trim();
            // 上期还款金额
            var minPayment = tds.get(2).text().trim();
            var date = tds.get(3).text().trim();
            var currency = tds.get(4).text().trim();
            var creditLimit = tds.get(5).text().trim();
            creditBill.setBillDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(billdate, "yyyy-MM-dd")));
            creditBill.setBillMonth(TimeUtil.getTimeStr(billdate, "yyyy-MM"));
            creditBill.setBankName("广发银行");
            creditBill.setBillType("DONE");
            creditBill.setBillId(UUID.randomUUID().toString());
            if (currency.equals("人民币")) {
                creditBill.setNewBalance(GetJiner(newBalance));
                creditBill.setMinPayment(GetJiner(minPayment));
                if (date.contains("无需")) {// 如果显示无需还款，那么自己计算还款日
                    var c = Calendar.getInstance();
                    if (StringUtils.isNotBlank(day)) {// 广发银行的还款日一直是固定的值，按照账单月+还款日计算
                        var paymentDay = creditBill.getBillMonth() + "-" + day;
                        var paymentDayLong = MyDateUtil.convergeTime(paymentDay);
                        c.setTimeInMillis(paymentDayLong);
                        if (billdate.getTime() > paymentDayLong) {// 如果账单月+还款日后时间小于账单日，还款日月份+1
                            c.add(Calendar.MONTH, 1);
                        }
                    } else {// 如果没取到还款日，那么时间之能是错的了。。。
                        c.setTime(billdate);
                        c.add(Calendar.DATE, 25);
                        logger.error(BankCode.CGB + " 还款日靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
                    }
                    creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(c.getTime(), "yyyy-MM-dd")));
                    var b = GetJiner(newBalance).multiply(new BigDecimal(-1));
                    creditBill.setNewBalance(b);
                } else {// 如果取到还款日，直接使用
                    var paydate = new Date(MyDateUtil.convergeTime(date));
                    creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(paydate, "yyyy-MM-dd")));
                }
                creditBill.setCreditLimit(GetJiner(creditLimit));
                creditBill.setCashLimit(creditBill.getCreditLimit().divide(new BigDecimal(2)));
            } else {

                creditBill.setUsdNewBalance(GetJiner(newBalance));
                creditBill.setUsdMinPayment(GetJiner(minPayment));
                if (date.contains("无需")) {// 如果显示无需还款，那么自己计算还款日
                    var c = Calendar.getInstance();
                    if (StringUtils.isNotBlank(day)) {// 广发银行的还款日一直是固定的值，按照账单月+还款日计算
                        var paymentDay = creditBill.getBillMonth() + "-" + day;
                        var paymentDayLong = MyDateUtil.convergeTime(paymentDay);
                        c.setTimeInMillis(paymentDayLong);
                        if (billdate.getTime() > paymentDayLong) {// 如果账单月+还款日后时间小于账单日，还款日月份+1
                            c.add(Calendar.MONTH, 1);
                        }
                    } else {// 如果没取到还款日，那么时间之能是错的了。。。
                        c.setTime(billdate);
                        c.add(Calendar.DATE, 25);
                        logger.error(BankCode.CGB + " 还款日靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
                    }
                    creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(c.getTime(), "yyyy-MM-dd")));
                    var b = GetJiner(newBalance).multiply(new BigDecimal(-1));
                    creditBill.setUsdNewBalance(b);
                } else {// 如果取到还款日，直接使用
                    var paydate = new Date(MyDateUtil.convergeTime(date));
                    creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(paydate, "yyyy-MM-dd")));
                }
                creditBill.setUsdCreditLimit(GetJiner(creditLimit));
                creditBill.setUsdCashLimit(creditBill.getUsdCreditLimit().divide(new BigDecimal(2)));
                logger.error(BankCode.CGB + " 其他货币抓取靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
            }
            var cardNumbers = cardNumber.trim().split(" ");
            var last4No ="";
            for each (var cardNo in cardNumbers) {
                if("".equals(last4No)){
                    last4No = getLast4Str(cardNo);
                }else{
                    last4No = last4No+"," + getLast4Str(cardNo);
                }
            }
            logger.info("任务taskKey = {}, last4No = {}", context.get(LUA_TASK_KEY), last4No);
            logger.info("任务taskKey = {}, last4No.split = {}", context.get(LUA_TASK_KEY), last4No.split);
            infos.put(last4No.split(","), creditBill);
            accountInfoFlag = true;

        }
    }

    if (!accountInfoFlag) {// 没有解析到账单周期
        logger.error(BankCode.CGB + " 么有解析到账户信息,taskkey {}",context.get(Constants.LUA_TASK_KEY));
        return null;
    }
    accountInfoFlag = false;
    var e = doc.select("#reportPanel5").select("#groupFooter1");
    if (e != null) {
        var trs = e.select("tr");
        for each (var element2 in trs) {
            var tds = element2.select("td");
            if (element2.text().contains("Card Number") || element2.text().contains("合  计") || tds.size() < 6) {
                continue;
            }
            var cardNumber = tds.get(0).text().trim();
            var	cardNumbers = cardNumber.split(" ");
            logger.info(BankCode.CGB + " 当前卡号" + cardNumber+",taskkey {}",context.get(Constants.LUA_TASK_KEY));
            var creditBill = null;
            for each (var billAllData in infos.entrySet()) {
                for each (var str in billAllData.getKey()) {
                    for each (var cardNo in cardNumbers) {
                        if(cardNo.contains(str)){
                            creditBill = billAllData.getValue();
                            break;
                        }
                    }
                }
            }
            if (creditBill == null) {
                logger.error(BankCode.CGB + " 详单解析出错,taskkey {}",context.get(Constants.LUA_TASK_KEY));
                return null;
            }
            var currency = tds.get(1).text().trim();
            // 上期账单金额
            var last_balance = tds.get(2).text().trim();
            // 上期还款金额
            var last_payment = tds.get(6).text().trim();
            last_payment = "-" + last_payment;
            // 本期新增款额
            var new_charges = tds.get(4).text().trim();
            if (new_charges.contains(" ")) {
                new_charges = new_charges.replace(" ", "+");
            }
            if (currency.equals("人民币")) {
                creditBill.setLastBalance(GetJiner(last_balance));
                //将已出账单最新的上月账单金额 ，存入集合，供未出账单时候
                if(baseMap.get(keys.UNDO_LAST_NEWBALANCE)==null){
                    baseMap.put(keys.UNDO_LAST_NEWBALANCE,GetJiner(last_balance));
                }
                creditBill.setNewCharges(GetJiner(new_charges));
            } else {
                creditBill.setUsdLastBalance(GetJiner(last_balance));
                creditBill.setUsdNewCharges(GetJiner(new_charges));
                logger.error(BankCode.CGB + " 其他货币抓取靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
            }
            accountInfoFlag = true;
        }
    }

    if (!accountInfoFlag) {// 没有解析到账单周期
        logger.error(BankCode.CGB + " 么有解析到本期应还信息,taskkey {}",context.get(Constants.LUA_TASK_KEY));
        return null;
    }
    var loopBand1 = doc.select("#loopBand1");
    if (loopBand1.size() >= 2) {
        logger.info(BankCode.CGB + " 和详单同级表格个数为 {},taskkey {}", loopBand1.size(),context.get(Constants.LUA_TASK_KEY));
        var loopBand2 = loopBand1.get(1).select("#loopBand2");
        if (loopBand2.size() == 0) {
            loopBand2 = loopBand1.get(0).select("#loopBand2");
        }
        for each (var element2 in loopBand2) {
            var cardNumber = element2.select("#groupHeader1").text();
            if (cardNumber.contains("（")) {
                cardNumber = cardNumber.substring(0, cardNumber.indexOf("（"));
            }
            logger.info(BankCode.CGB + " 当前卡号,taskkey {}" + cardNumber,context.get(Constants.LUA_TASK_KEY));
            var card_num = getLast4Str(cardNumber);
            var creditBill = null;
            for each (var billAllData in infos.entrySet()) {
                for each (var str in billAllData.getKey()) {
                    if(card_num.contains(str)){
                        creditBill = billAllData.getValue();
                    }
                }
            }
            var fixBand7 = element2.select("#fixBand7");
            // var bills = new ArrayList();
            if(creditBill==null){
                return null;
            }

            bills=creditBill.getShoppingSheets();
            //creditBill.setShoppingSheets(bills);
            if (fixBand7.size() < 1) {
                logger.error(BankCode.CGB + " 账单解析不服规则 长度小于1 {},taskkey {}", fixBand7.size(),context.get(Constants.LUA_TASK_KEY));
                return null;
            }
            var trs1 = fixBand7.select("tr");
            var billId = 0;
            for each (var element3 in trs1) {
                if (element3.select("td").size() < 5) {
                    continue;
                }
                var jiaoyiri = element3.select("td").get(0).text();
                var ruzhangri = element3.select("td").get(1).text();
                var zhaiyao = element3.select("td").get(2).text();
                var jiaoyijiner = element3.select("td").get(3).text();
                var jiaoyihuobi = element3.select("td").get(4).text();
                var ruzhangjiner = element3.select("td").get(5).text();
                if (StringUtils.isBlank(jiaoyiri) || !jiaoyiri.matches("\\d{4}-\\d{2}-\\d{2}")) {
                    continue;
                }

                var billdatail = createExpense(++billId, card_num, jiaoyiri, zhaiyao, jiaoyihuobi, jiaoyijiner, ruzhangri, ruzhangjiner);
                bills.add(billdatail);
            }

            if (isDebug) {
                System.out.println(JSON.toJSON(creditBill));
            }
        }
    } else {
        logger.error(BankCode.CGB + " 详单解析出错,taskkey {}",context.get(Constants.LUA_TASK_KEY));
    }
    return infos;
}

/**
 * 通过网页解析账单
 *
 * @param map
 * @param jsonStr
 * @return
 */
function parserBills3(creditCardAllData,  jsonStr) {
    var map=new HashMap;
    var doc = Jsoup.parse(jsonStr);
    var billdate = null;
    var fixBand5 = doc.select("#fixBand5");
    if (fixBand5.size() < 1) {
        logger.error(BankCode.CGB + " 账单周期解析不符规则 长度为 {},taskkey {}", fixBand5.size(),context.get(Constants.LUA_TASK_KEY));
        return null;
    }
    var startData = null;
    var endData = null;
    var infos = new LinkedHashMap();
    var BillDateflag = false;
    for each(var element in fixBand5) {
        var text = element.text();
        if (text.contains("账单周期")) {
            var billDate = element.select("td").get(2).text();
            var date = billDate.split("-");
            startData = date[0].replaceAll(" ", "").trim();
            endData = date[1].replaceAll(" ", "").trim();
            // creditBill.setBillDate(processDate(endData));
            billdate = new Date(MyDateUtil.convergeTime(endData));
            map.put("beginDate", startData);
            map.put("endDate", endData);
            BillDateflag = true;
            break;
        }
    }
    if (!BillDateflag) {// 没有解析到账单周期
        logger.error(BankCode.CGB + " 么有解析到账单周期,尝试下一解析方法,taskkey {}",context.get(Constants.LUA_TASK_KEY));
        return parserBills3_(creditCardAllData, jsonStr);// 一个卡两个账户的不能兼容,只能新增方法
    }
    var accountInfoFlag = false;
    var fixBand2 = doc.select("#fixBand2>table");
    if (fixBand2.size() > 0) {
        for each (var element in fixBand2) {
            var text = element.text();
            if (text.contains("信用卡账户信息") && text.contains("客户消费额度 Total Credit Limit")) {
                var trs = element.select("#fixBand7");
                for each (var element2 in trs) {
                    var tds = element2.select("td");
                    if (tds.size() < 5) {
                        continue;
                    }
                    //现获取到一个可用的已出账单的billAllData
                    var creditBill = getDoneBillAllDataHeaderData(creditCardAllData);
                    // var creditBill = getBillAllData();
                    var cardNumber = tds.get(0).text().trim();
                    // 上期账单金额
                    var newBalance = tds.get(1).text().trim();
                    // 上期还款金额
                    var minPayment = tds.get(2).text().trim();
                    var date = tds.get(3).text().trim();
                    var currency = tds.get(4).text().trim();
                    var creditLimit = tds.get(5).text().trim();
                    creditBill.setBillDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(billdate, "yyyy-MM-dd")));
                    creditBill.setBillMonth(TimeUtil.getTimeStr(billdate, "yyyy-MM"));
                    creditBill.setBankName("广发银行");
                    creditBill.setBillType("DONE");
                    creditBill.setBillId(UUID.randomUUID().toString());
                    if (currency.equals("人民币")) {
                        creditBill.setNewBalance(GetJiner(newBalance));
                        //只获取已出账单最新一个月的数据
                        if(baseMap.get(keys.UNDO_NEWBALANCE)==null){
                            baseMap.put(keys.UNDO_NEWBALANCE,GetJiner(newBalance))
                        }
                        creditBill.setMinPayment(GetJiner(minPayment));
                        if (date.contains("无需")) {// 如果显示无需还款，那么自己计算还款日
                            var c = Calendar.getInstance();
                            if (StringUtils.isNotBlank(day)) {// 广发银行的还款日一直是固定的值，按照账单月+还款日计算
                                var paymentDay = creditBill.getBillMonth() + "-" + day;
                                var paymentDayLong = MyDateUtil.convergeTime(paymentDay);
                                c.setTimeInMillis(paymentDayLong);
                                if (billdate.getTime() > paymentDayLong) {// 如果账单月+还款日后时间小于账单日，还款日月份+1
                                    c.add(Calendar.MONTH, 1);
                                }
                            } else {// 如果没取到还款日，那么时间之能是错的了。。。
                                c.setTime(billdate);
                                c.add(Calendar.DATE, 25);
                                logger.error(BankCode.CGB + " 还款日靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
                            }
                            creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(c.getTime(), "yyyy-MM-dd")));
                            var b = GetJiner(newBalance).multiply(new BigDecimal(-1));
                            creditBill.setNewBalance(b);
                        } else {// 如果取到还款日，直接使用
                            var paydate = new Date(MyDateUtil.convergeTime(date));
                            creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(paydate, "yyyy-MM-dd")));
                        }
                        creditBill.setCreditLimit(GetJiner(creditLimit));
                        creditBill.setCashLimit(creditBill.getCreditLimit().divide(new BigDecimal(2)));
                    } else {

                        creditBill.setUsdNewBalance(GetJiner(newBalance));
                        creditBill.setUsdMinPayment(GetJiner(minPayment));
                        if (date.contains("无需")) {// 如果显示无需还款，那么自己计算还款日
                            var c = Calendar.getInstance();
                            if (StringUtils.isNotBlank(day)) {// 广发银行的还款日一直是固定的值，按照账单月+还款日计算
                                var paymentDay = creditBill.getBillMonth() + "-" + day;
                                var paymentDayLong = MyDateUtil.convergeTime(paymentDay);
                                c.setTimeInMillis(paymentDayLong);
                                if (billdate.getTime() > paymentDayLong) {// 如果账单月+还款日后时间小于账单日，还款日月份+1
                                    c.add(Calendar.MONTH, 1);
                                }
                            } else {// 如果没取到还款日，那么时间之能是错的了。。。
                                c.setTime(billdate);
                                c.add(Calendar.DATE, 25);
                                logger.error(BankCode.CGB + " 还款日靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
                            }
                            creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(c.getTime(), "yyyy-MM-dd")));
                            var b = GetJiner(newBalance).multiply(new BigDecimal(-1));
                            creditBill.setUsdNewBalance(b);
                        } else {// 如果取到还款日，直接使用
                            var paydate = new Date(MyDateUtil.convergeTime(date));
                            creditBill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(paydate, "yyyy-MM-dd")));
                        }
                        creditBill.setUsdCreditLimit(GetJiner(creditLimit));
                        creditBill.setUsdCashLimit(creditBill.getUsdCreditLimit().divide(new BigDecimal(2)));
                        logger.error(BankCode.CGB + " 其他货币抓取靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
                    }
                    var cardNumbers = null;
                    cardNumbers = cardNumber.split(" ");
                    var last4No = "";
                    for each (var cardNo in cardNumbers) {
                        if("".equals(last4No)){
                            last4No = getLast4Str(cardNo);
                        }else{
                            last4No = last4No+","+getLast4Str(cardNo);
                        }
                    }
                    logger.info("任务taskKey = {}, last4No = {}", context.get(LUA_TASK_KEY), last4No);
                    logger.info("任务taskKey = {}, last4No.split = {}", context.get(LUA_TASK_KEY), last4No.split);
                    //放入集合，供外层使用
                    baseMap.put(keys.LAST4No,last4No);
                    infos.put(last4No.split(","), creditBill);
                    accountInfoFlag = true;
                }
                continue;
            }
            if (text.contains("上期应还总额") && text.contains("本期应还总额") && !text.contains("交易摘要")) {
                var e = element.select("#fixBand4");
                if (e != null) {
                    var trs = e.select("tr");
                    for each (var element2 in trs) {
                        var tds = element2.select("td");
                        if (tds.size() < 5 || tds.text().contains("Card Number")) {
                            continue;
                        }
                        var cardNumber = tds.get(0).text().trim();
                        var cardNumbers = cardNumber.split(" ");
                        var creditBill = null;
                        for each (var billAllData in infos.entrySet()) {
                            for each (var str in billAllData.getKey()) {
                                for each (var numbers in cardNumbers) {
                                    if(numbers.contains(str)){
                                        creditBill = billAllData.getValue();
                                        break;
                                    }
                                }
                            }
                        }

                        if (creditBill == null) {
                            logger.error(BankCode.CGB + " 详单解析出错,taskkey {}",context.get(Constants.LUA_TASK_KEY));
                            return null;
                        }
                        var currency = tds.get(1).text().trim();
                        // 上期账单金额
                        var last_balance = tds.get(2).text().trim();
                        // 上期还款金额
                        var last_payment = tds.get(6).text().trim();
                        last_payment = "-" + last_payment;
                        // 本期新增款额
                        var new_charges = tds.get(4).text().trim();
                        if (currency.equals("人民币")) {
                            creditBill.setLastBalance(GetJiner(last_balance));
                            //只获取已出账单最新一个月的数据
                            if(baseMap.get(keys.UNDO_LAST_NEWBALANCE)==null){
                                baseMap.put(keys.UNDO_LAST_NEWBALANCE,GetJiner(last_balance))
                            }
                            creditBill.setLastPayment(GetJiner("-"+last_payment));
                            creditBill.setNewCharges(GetJiner(new_charges));
                        } else {
                            creditBill.setLastPayment(GetJiner("-"+last_payment));
                            creditBill.setUsdLastBalance(GetJiner(last_balance));
                            creditBill.setUsdNewCharges(GetJiner(new_charges));
                            logger.error(BankCode.CGB + " 其他货币抓取靠猜 {},taskkey {}", currency,context.get(Constants.LUA_TASK_KEY));
                        }
                    }
                }
            }
        }
    }
    if (!accountInfoFlag) {// 没有解析到账单周期
        logger.error(BankCode.CGB + " 么有解析到账户信息,taskkey {}",context.get(Constants.LUA_TASK_KEY));
        return null;
    }
    var loopBand1 = doc.select("#loopBand1");
    if (loopBand1.size() >= 2) {
        logger.info(BankCode.CGB + " 和详单同级表格个数为 {},taskkey {}", loopBand1.size(),context.get(Constants.LUA_TASK_KEY));
        var loopBand2 = loopBand1.get(1).select("#loopBand2");
        for each (var element2 in loopBand2) {
            var cardNumber = element2.select("#groupHeader1").text();
            var card_num = getLast4Str(cardNumber);
            var cardNumbers = cardNumber.split(" ");
            var creditBill = null;
            for each (var billAllData in infos.entrySet()) {
                for each (var str in billAllData.getKey()) {
                    for each (var numbers in cardNumbers) {
                        if(numbers.contains(str)){
                            creditBill = billAllData.getValue();
                            break;
                        }
                    }
                }
            }
            var fixBand7 = element2.select("#fixBand7");
            var bills = new ArrayList();
            if(creditBill!=null){
                //从对象中取出
                bills=creditBill.getShoppingSheets();
                //creditBill.setShoppingSheets(bills);
                if (fixBand7.size() < 1) {
                    logger.error(BankCode.CGB + " 账单解析不服规则 长度小于1 {},taskkey {}", fixBand7.size(),context.get(Constants.LUA_TASK_KEY));
                    return null;
                }
                var trs1 = fixBand7.select("tr");
                var billId = 0;
                for each (var element3 in trs1) {
                    if (element3.select("td").size() < 5) {
                        continue;
                    }
                    var jiaoyiri = element3.select("td").get(0).text();
                    var ruzhangri = element3.select("td").get(1).text();
                    var zhaiyao = element3.select("td").get(2).text();
                    var jiaoyijiner = element3.select("td").get(3).text();
                    var jiaoyihuobi = element3.select("td").get(4).text();
                    var ruzhangjiner = element3.select("td").get(5).text();
                    if (StringUtils.isBlank(jiaoyiri) || !jiaoyiri.matches("\\d{4}-\\d{2}-\\d{2}")) {
                        continue;
                    }

                    var billdatail = createExpense(++billId, card_num, jiaoyiri, zhaiyao, jiaoyihuobi, jiaoyijiner, ruzhangri, ruzhangjiner);
                    bills.add(billdatail);
                }

                if (isDebug) {
                    System.out.println(JSON.toJSON(creditBill));
                }
            }
        }
    } else {
        logger.error(BankCode.CGB + " 详单解析出错,taskkey {}",context.get(Constants.LUA_TASK_KEY));
    }
    return infos;
}


/**
 * 创建账单明细并填充相应数据
 *
 * @param id
 * @param card_num
 * @param jiaoyiri
 * @param zhaiyao
 * @param jiaoyihuobi
 * @param jiaoyijiner
 * @param ruzhangri
 * @param ruzhangjiner
 * @return
 */
function createExpense( id,  card_num,  jiaoyiri,  zhaiyao,  jiaoyihuobi,  jiaoyijiner,
                        ruzhangri,  ruzhangjiner) {
    var billdatail = getExpense();
    if (StringUtils.isNotBlank(zhaiyao)) {
        zhaiyao = zhaiyao.replaceAll(" ", "");
    }
    billdatail.setId(UUID.randomUUID().toString());// 账单id
    billdatail.setCardNum(card_num);// 卡号后四位
    billdatail.setPostDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(new Date(MyDateUtil.convergeTime(jiaoyiri)), "yyyy-MM-dd")));// 记账时间
    billdatail.setOrderIndex(id);
    billdatail.setTransDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(new Date(MyDateUtil.convergeTime(jiaoyiri)))));// 交易日期
    billdatail.setCurrencyType("CNY");// 货比
    billdatail.setAmountMoney(GetJiner(jiaoyijiner));// 交易金额
    billdatail.setCategory(classify(zhaiyao, billdatail.getAmountMoney()));// 交易类型
    // billdatail.setTransAddr("");
    // billdatail.setTransMethod("");
    // billdatail.setTransChannel("");
    billdatail.setDescription(zhaiyao);// 摘要
    // billdatail.setRemark("");
    var o = new Object(jiaoyiri, ruzhangri, jiaoyijiner, jiaoyihuobi, ruzhangjiner, zhaiyao );
    // logger.info("交易日 : {},入账日 : {},交易金额 : {},交易货币 : {},入账金额 : {},户口交易摘要 : {}",
    // o);
    return billdatail;
}

